package controllers

import (
	"github.com/astaxie/beego"
	"hello/conf"
	"hello/lib"
	"hello/lib/mysqlLib"
	"hello/lib/redisLib"
	"log"
	"strconv"
	"strings"
)

type Home struct {
	beego.Controller
}

//type Privilege struct {
//	Priv string `json:"privilege"`
//}
type OAuthTokenResp struct {
	OAuthAccessToken string `json:"access_token"`
	ExpiresIn int `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
	Openid string `json:"openid"`
	Scope string `json:"scope"`
}
/*
 *	{
 *		"openid":" OPENID",
 *		"nickname": NICKNAME,
 *		"sex":"1",
 *		"province":"PROVINCE",
 *		"city":"CITY",
 *		"country":"COUNTRY",
 *		"headimgurl":       "http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
 *		"privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
 *		"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
 *	}
 */
type UserInfo struct {
	Openid string `json:"openid"`
	Nickname string  `json:"nickname"`
	Sex int `json:"sex"`
	Province string `json:"province"`
	City string `json:"city"`
	Country string `json:"country"`
	Headimgurl string `json:"headimgurl"`
	//Privileges []Privilege `json:"privileges"`
	Unionid string `json:"unionid"`
}
type TokenRespErr struct {
	Errcode int `json:"errcode"`
	Errmsg string `json:"errmsg"`
}

type GatewayInfo struct {
	GatewayID string
	GatewayName string
}
func (h *Home) Get() {
	h.TplName = "home.html"
	//token 获取会话cookie，即拿到token。
	//h.Ctx.SetCookie(conf.OpenidIdCookieId, "")
	sessionToken := h.Ctx.GetCookie(conf.UseridIdCookieId)
	if sessionToken == "" {
		// token为空，重新获取用户授权并获得openID和当前时间戳，并进行base64编码，存入redis，设置cookie
		// 重定向至微信授权页面
		authUrl := strings.Replace(conf.OAuth2Url, "APPID", conf.AppId, 1)
		authUrl = strings.Replace(authUrl, "REDIRECT_URI", conf.RedirectUri, 1)
		oauthtext := "<script type=\"application/javascript\">alert(\"请授权后再访问！\");window.location.href=\"" + authUrl + "\"</script>"
		log.Printf("oauthtext :%s", oauthtext)
		h.Data["oAuthText"] = oauthtext
		log.Println("已授权")

	} else {
		//log.Printf("session token:%s", sessionToken)
		// get token and query in redis, return openid
		user, err := redisLib.Get(redisLib.Session, sessionToken)
		if err != nil {
			// error process
			log.Printf("redis get key error :%s", err)
			return
		}
		u,err := strconv.Atoi(user)
		//log.Printf("userid is :%d", u)
		h.Data["Userid"] = u
		// query band gateway in mysql with openid/userid, return gateway id
		sqlStr := "select gateway_id,gateway_name from hh_gateway_band_RT where user_id = ?;"
		var GatewayInfoList []GatewayInfo
		var GatewayInfo GatewayInfo
		var dest1, dest2 []byte

		db := mysqlLib.NewConnection()
		defer db.Close()
		rows, err := db.Query(sqlStr, user)
		if rows != nil {
			for rows.Next() {
				err := rows.Scan(&dest1, &dest2)
				if err != nil {
					log.Printf("query gatewayid error : %s", err.Error())
				}
				GatewayInfo.GatewayID = lib.B2S(dest1)
				GatewayInfo.GatewayName = lib.B2S(dest2)
				GatewayInfoList = append(GatewayInfoList, GatewayInfo)
			}
		} else {
			h.Data["errNoBandMsg"] = "<div class=\"weui-panel__hd\">您当前未绑定设备,请进行绑定!</div>"
		}
		if len(GatewayInfoList) == 0 {
			h.Data["errNoBandMsg"] = "<div class=\"weui-panel__hd\">您当前未绑定设备,请进行绑定!</div>"
			}
		h.Data["GatewayInfoList"] = GatewayInfoList
	}
}